package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrderMapper orderMapper;


    @Scheduled(cron =  "0 * * * * ?")// 每一分钟执行
    public void processTimeOrder() {
        log.info("取消单操作");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> l = orderMapper.selectStatusAndTime(Orders.PENDING_PAYMENT, time);
        if (l.size() != 0) {
            for (Orders orders : l) {
                orders.setStatus(Orders.CANCELLED); // 改状态为取消的
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now()); // 更新的取消时间
//            进行更新的操作
                orderMapper.update(orders);
            }
        }
    }


    @Scheduled(cron =  "0 0 1 * * ?")// 每天的1点钟执行
    public void tipTimeOrder(){
        log.info("订单已完成，自动更改状态为完成");
        LocalDateTime t = LocalDateTime.now().plusMinutes(-60);
        List<Orders> orders = orderMapper.selectStatusAndTime(Orders.DELIVERY_IN_PROGRESS, t);
        if (orders.size() > 0){
            for (Orders order : orders) {
                order.setStatus(Orders.COMPLETED);
                //            进行更新的操作
                orderMapper.update(order);
            }
        }
    }
}
